<template>
  <a-modal
    v-model:visible="visible"
    :ok-loading="confirmLoading"
    :centered="false"
    :closable="false"
    unmount-on-close
    @ok="handleSave"
    @cancel="handleConfirmCancel"
    ok-text="保存"
    :modal-style="{ top: '0', bottom:'0', width: '100%', height: '100%' }"
    :body-style="{ padding: '0' }"
  >
    <a-spin :spinning="confirmLoading">
      <a-tabs default-active-key="1" v-model:active-key="basicActiveKey" @change="basicActiveKeyChange">
        <a-tab-pane
          key="基本配置"
          title="基本配置"
          v-if="['add','edit','noCodeAdd','noCodeEdit','artAdd','artEdit','dataView','nodeAdd','nodeEdit'].includes(this.mode)">
          <basic-config ref="basicConfig"></basic-config>
        </a-tab-pane>
        <a-tab-pane key="表单设计" title="表单设计">
          <a-row type="flex" justify="start" :gutter="[0, 0]">
            <a-col :span="4">
              <form-left ref="formLeft"></form-left>
            </a-col>
            <a-col :span="15">
              <form-page ref="formPage"></form-page>
            </a-col>
            <a-col :span="5">
              <form-right ref="formRight"></form-right>
            </a-col>
          </a-row>
        </a-tab-pane>
        <a-tab-pane key="功能相关" :title="['add','edit'].includes(mode) ?'按钮功能':'功能相关'" v-if="['add','edit','noCodeAdd','noCodeEdit'].includes(mode)">
          <button-config></button-config>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </a-modal>
</template>

<script>
import { formItemModalLayout } from '@/common/constant'
// import _ from 'lodash'
import FormLeft from './FormLeft.vue'
import FormPage from './FormPage.vue'
import FormRight from './FormRight.vue'
import BasicConfig from './BasicConfig.vue'
import ButtonConfig from './ButtonConfig.vue'
import { nanoid } from 'nanoid'
import { basicDefaultData } from './base/options'
import Router from 'vue-router'
// import { constantRouterMap } from '@/config/router.config'
import store from '@/store'
import _ from 'lodash'
import { filterNodesByFieldValue, mergeWithNonEmpty, repairUiData, repairUiSort, repairUiButtonData } from '../../utils/util'
import { setFocusToFirstFocusableElement } from '../../mixins/methodsMixins'

const buttonGroup = [
  {
    checked: true,
    hideButton: false,
    displayFields: [],
    buttonEventAddDTO: { eventType: 'query' },
    tableButtonAddDTO: {
      buttonName: '查询',
      buttonType: 'top',
      buttonIcon: 'search',
      defaultFlag: true,
      buttonAfter: 'flash',
      menuFlag: '1'
    }
  },
  {
    checked: true,
    hideButton: false,
    displayFields: [],
    buttonEventAddDTO: { eventType: 'add' },
    tableButtonAddDTO: {
      buttonName: '新增',
      buttonType: 'top',
      buttonIcon: 'plus',
      defaultFlag: true,
      buttonAfter: 'flash'
    }
  },
  {
    checked: true,
    hideButton: false,
    displayFields: [],
    buttonEventAddDTO: { eventType: 'update' },
    tableButtonAddDTO: {
      buttonName: '编辑',
      buttonType: 'data',
      buttonIcon: 'edit',
      defaultFlag: true,
      buttonAfter: 'flash',
      routeType: 'desc',
      rendering: '1' // 流程中使用此按钮可以选择数据进行操作
    }
  },
  {
    checked: true,
    hideButton: false,
    displayFields: [],
    buttonEventAddDTO: { eventType: 'del' },
    tableButtonAddDTO: {
      buttonName: '删除',
      buttonType: 'data',
      buttonIcon: 'delete',
      defaultFlag: true,
      buttonAfter: 'flash',
      rendering: '1'
    }
  },
  {
    checked: false,
    hideButton: false,
    displayFields: [],
    buttonEventAddDTO: { eventType: 'import' },
    tableButtonAddDTO: {
      buttonName: '导入',
      buttonType: 'top',
      buttonIcon: 'import',
      defaultFlag: true,
      buttonAfter: 'flash',
      rendering: '1'
    }
  },
  {
    checked: false,
    hideButton: false,
    displayFields: [],
    buttonEventAddDTO: { eventType: 'export' },
    tableButtonAddDTO: {
      buttonName: '导出',
      buttonType: 'top',
      buttonIcon: 'export',
      defaultFlag: true,
      buttonAfter: 'flash',
      rendering: '1'
    }
  },
  {
    checked: false,
    hideButton: false,
    displayFields: [],
    columnNum: 2,
    buttonEventAddDTO: { eventType: 'details' },
    tableButtonAddDTO: {
      buttonName: '详情',
      buttonType: 'data',
      buttonIcon: 'snippets',
      defaultFlag: false,
      buttonAfter: 'flash',
      rendering: '1'
    }
  },
  {
    checked: false,
    hideButton: false,
    displayFields: [],
    buttonEventAddDTO: { eventType: 'batchDel' },
    tableButtonAddDTO: {
      buttonName: '批量删除',
      buttonType: 'top',
      buttonIcon: 'delete',
      defaultFlag: true,
      buttonAfter: 'flash',
      rendering: '1'
    }
  }
]
export default {
  name: 'FormDesigner',
  components: { ButtonConfig, BasicConfig, FormLeft, FormPage, FormRight },
  data () {
    return {
      mode: '', // 模式
      tableDesc: {}, // 详情数据
      basicActiveKey: '基本配置',
      basicSubActiveKey: '数据库属性',
      basicData: {
        prefixWay: '', // 前缀方式
        primaryPrefix: '', // 主键前缀
        sort: 0, // 改成默认0
        upFuncId: 0,
        dbRoleType: 'none',
        appType: 'task', // 无代码表单
        showType: 'data',
        cardShowField: '', // 表头展示值 fangyan
        columnList: '', // 字段权限
        upColumn: '', // 树结构的父级字段
        tenant: true, // 该表单是否需要租户字段
        pseudoFlag: false, // 是否伪表
        delFlag: false // 是否逻辑删除
      }, // 基础配置
      pageData: [], // 动态数据
      defaultKeys: [], // 默认有的字段
      buttonData: _.cloneDeep(buttonGroup), // 表单总体配置
      buttonLength: buttonGroup.length, // 默认按钮数量
      sortData: [], // 字段排序数组
      rulesData: [], // 校验字段规则
      allFormConfig: {
        labelWidth: 120,
        labelAlign: 'left',
        isMobile: false,
        modalWidth: 800,
        modalHeight: 700
      }, // 整体表单配置
      tableExConfig: [], // 外键配置
      exKeysData: [], // 外键查询配置用的
      openSearchExKey: false,
      visible: false,
      confirmLoading: false,
      formItemModalLayout,
      isShow: false,
      selectIndex: undefined, // 当前选择的行下标
      cloneData: undefined,
      upFuncIds: [], // 上级菜单
      userGroupList: [] // 用户组列表
    }
  },
  // 父组件中返回要传给下级的数据
  provide () {
    return {
      dataObj: this
    }
  },
  methods: {
    basicActiveKeyChange () {
      // eslint-disable-next-line no-unused-expressions
      this.$refs.basicConfig?.setExKeyData()
    },
    open (mode, record) {
      const modeMap = new Map([
        ['add', { title: '新增', mode: 'add' }],
        ['edit', { title: '编辑', mode: 'edit' }],
        ['nodeAdd', { title: '节点新增', mode: 'nodeAdd' }],
        ['nodeEdit', { title: '节点编辑', mode: 'nodeEdit' }],
        ['noCodeAdd', { title: '无代码表单添加', mode: 'noCodeAdd' }],
        ['noCodeEdit', { title: '无代码表单编辑', mode: 'noCodeEdit' }],
        ['artAdd', { title: '视图表单添加', mode: 'artAdd' }],
        ['artEdit', { title: '视图表单编辑', mode: 'artEdit' }],
        ['dataView', { title: '数据源视图', mode: 'dataView' }],
        ['parseForm', { title: '解析后台数据展示', mode: 'parseForm' }]
      ])
      this.modeInfo = modeMap.get(mode) || {}
      this.mode = this.modeInfo?.mode
      console.log('进入的模式及数据:', this.mode, record)
      this.visible = true
      if (this.mode === 'add') {
        this.queryDefaultKey()
        this.queryMenuList()
        this.queryUseGroup()
      } else if (this.mode === 'edit') {
        // open
        this.queryMenuList()
        this.queryUseGroup()
        this.queryTableDesc(record)
      } else if (this.mode === 'nodeAdd') {
        this.basicActiveKey = '表单设计'
        this.gettableDesc(record)
      } else if (this.mode === 'nodeEdit') {
        this.basicActiveKey = '表单设计'
        this.gettableDesc(record)
        this.getNodeDesc(record)
        this.rulesData = this.setTableRulesData(JSON.parse(record))
      } else if (this.mode === 'artEdit') {
        this.getArtDesc(record)
      } else if (this.mode === 'noCodeEdit') {
        this.queryTableDesc(record)
      } else if (this.mode === 'dataView') {
        this.getDataViewDesc(record)
        this.queryGroupList = record.queryGroupList.concat(record.groupByGroupList) // 字段Key选项
      }
        this.setFocusToFirstFocusableElement()
    },
    setFocusToFirstFocusableElement,
    async queryUseGroup () {
      try {
        const result = await this.$http.get('/usergroup/queryListMongo')
        console.log('result', result)
        this.userGroupList = result.data
      } catch (e) {
        console.error('请求错误', e)
      }
    },
    // 查询一级菜单
    async queryMenuList () {
      try {
        const { data: {
          funcList
        } } = await this.$http.get('/funcinfo/funcUpList') // funcList
        // 插入一个无的选项
        funcList.unshift({ funcName: '无', _id: 0 }) // 表单创建的菜单不能作为一级菜单
        this.upFuncIds = filterNodesByFieldValue(funcList, 'funcType', ['table'])
      } catch (e) {
        console.error('请求错误', e)
      }
    },
    // 数据源编辑视图解析内容
    getDataViewDesc (record) {
      const { viewId, viewUi, dataSourceUiMapDTOList } = record
      this.tableDesc = _.cloneDeep({
        ...record,
        formId: viewId
      })
      let formUi = viewUi && viewUi || '{}'
      formUi = repairUiData(formUi, dataSourceUiMapDTOList) // 修复数据源UI数据
      Object.keys(formUi).forEach(key => {
        if (key === 'pageData') {
          // eslint-disable-next-line no-return-assign
          // 对于pageData中的每个对象，合并formData
          formUi[key] = formUi[key].map(item => ({
            ...item, // 保留原有属性
            formData: {
              ...basicDefaultData(), // 添加或覆盖formData属性，使用基础数据模板
              ...item.formData, // 确保保留item.formData中原有的值（如果有）
              notMod: true
            }
          }))
        }
        this[key] = formUi[key]
      })
    },
    getArtDesc (record) {
      const { viewDataMappingDTOList: dataSourceUiMapDTOList, processViewQueryDTO } = record
      const { viewId, viewUi } = processViewQueryDTO
      this.tableDesc = _.cloneDeep({
        ...record,
        formId: viewId
      })
      let formUi = viewUi && viewUi || '{}'
      formUi = repairUiData(formUi, dataSourceUiMapDTOList)
      Object.keys(formUi).forEach(key => {
        if (key === 'pageData') {
          // 对于pageData中的每个对象，合并formData
          formUi[key] = formUi[key].map(item => {
            return {
              ...item, // 保留原有属性
              formData: {
                ...basicDefaultData(), // 添加或覆盖formData属性，使用基础数据模板
                ...item.formData, // 确保保留item.formData中原有的值（如果有）
                notMod: true
              }
            }
          })
        }
        this[key] = formUi[key]
      })
    },
    gettableDesc (record) {
      // 处理视图表单回显问题
      const formUi = record && JSON.parse(record) || {}
      const { tableDesc } = formUi
      this.tableDesc = {
        ...this.tableDesc,
        ...tableDesc
      }
    },
    getNodeDesc (record) {
      const formUi = record && JSON.parse(record) || {}
      Object.keys(formUi).forEach(key => {
        if (key === 'pageData') {
          // eslint-disable-next-line no-return-assign
          // 对于pageData中的每个对象，合并formData
          formUi[key] = formUi[key].map(item => ({
            ...item, // 保留原有属性
            formData: {
              ...basicDefaultData(), // 添加或覆盖formData属性，使用基础数据模板
              ...item.formData, // 确保保留item.formData中原有的值（如果有）
              notMod: true
            }
          }))
        }
        this[key] = formUi[key]
      })
    },
    // 设计表单详细查询
    async queryTableDesc (record) {
      try {
        const { formId, appId, appVersion, appName } = record
        this.confirmLoading = true
        const result = this.mode === 'noCodeEdit' ? await this.$http.post('/appEdit/newVersionEdit', {
            appId,
            appVersion,
            appName
          })
          : await this.$http.get('/tableInfo/queryTableDesc', { params: { formId } })
        // this.tableDesc = {
        //   ...result.data
        // }
        if (this.mode === 'noCodeEdit') {
          this.tableDesc = _.cloneDeep({
            ...result.data,
            appId: result.data.formInfoAddDTO.appId,
            appVersion: result.data.formInfoAddDTO.appVersion
          })
          this.oldAppName = appName
        } else {
          this.tableDesc = _.cloneDeep({
            ...result.data,
            formId: result.data.tableInfoAddDTO.formId
          })
        }
        let formUi = this.mode === 'noCodeEdit' ? result.data.formInfoAddDTO.formUi
          : result.data.tableUiAddDTO.formUi
        const { dataSourceUiMapDTOList } = result.data
        formUi = repairUiData(formUi, dataSourceUiMapDTOList) // 修复数据源UI数据
        formUi = repairUiSort(formUi, result.data.funcInfoAddDTO?.sort || 0) // 替换sort
        formUi = repairUiButtonData(formUi, result.data) // 替换ButtonData
        console.log(formUi, '查看结果', dataSourceUiMapDTOList)
        Object.keys(formUi).forEach(key => {
          if (key === 'pageData') {
            // 对于pageData中的每个对象，合并formData
            formUi[key] = formUi[key].map(item => {
              return {
                ...item, // 保留原有属性
                formData: {
                  ...basicDefaultData(), // 添加或覆盖formData属性，使用基础数据模板
                  ...item.formData, // 确保保留item.formData中原有的值（如果有）
                  notMod: true
                }
              }
            })
          }
           // 打个补丁，defaultKeys的name应该都为defaultKey,之前写了exkey
          if (key === 'defaultKeys') {
            // eslint-disable-next-line no-return-assign
            formUi[key].forEach(item => item.name = 'defaultKey')
          }
          if (key !== 'buttonData' || this.mode === 'noCodeEdit') {
            this[key] = formUi[key]
          } else {
            const { tableButtonReqDTOList } = result.data
            // eslint-disable-next-line no-return-assign
            this.buttonData.forEach(e => e.checked = false)// 清除现有按钮数据的状态，将所有按钮的 checked 属性设置为 false
            // eslint-disable-next-line no-unused-expressions
            tableButtonReqDTOList?.forEach(item => {
              // 这里后端返回的是字符串,我们要的是布尔类型
              if (item.buttonEventAddDTO.eventType === 'plug') {
                item.buttonEventAddDTO.foreignId = +item.buttonEventAddDTO.foreignId
              }
              if (!_.isArray(item.eventColumnMappingAddDTOList)) {
                item.eventColumnMappingAddDTOList = []
              }
              if (!item.chartConfig) { // 解析图表配置
                item.chartConfig = JSON.parse(item.buttonEventAddDTO.param)
              }
              const index = this.buttonData.findIndex(e => e.tableButtonAddDTO.buttonName === item.tableButtonAddDTO.buttonName)
              const uiData = formUi['buttonData'].find(e => e.tableButtonAddDTO.buttonName === item.tableButtonAddDTO.buttonName) || {}// UI中的按钮数据
              if (index > -1) {
                this.buttonData.splice(index, 1, mergeWithNonEmpty(this.buttonData[index], uiData, item))
              } else {
                this.buttonData.push(mergeWithNonEmpty({}, uiData, item))
              }
            })
          }
        })
        // 下面处理后台数据，需要返显的字段
        const { tableInfoAddDTO, funcInfoAddDTO } = result.data
        const { formName, cardShowField } = tableInfoAddDTO || {}
        const { upFuncId } = funcInfoAddDTO || {}
        if (formName) {
          // 使用后台数据的表单名称
          this.basicData.formName = formName
        }
        if (upFuncId || upFuncId === 0) {
          // 使用后台数据的上级菜单ID
          this.basicData.upFuncId = upFuncId
        }
        if (cardShowField) {
          this.basicData.cardShowField = cardShowField
        }
        // 处理tableExConfig的数据
        this.filterTableExConfig(result.data)
        // 设置rulesData
        this.rulesData = this.setTableRulesData(result.data)

        this.sortData = this.setTableSortData(result.data)

        // this.$refs['basicConfig'].setExKeyData() // 设置exKeysData
      } catch (e) {
        console.error('请求失败', e)
      } finally {
        this.confirmLoading = false
      }
    },
    setTableSortData (data) {
      const { tableQueryOrderAddDTOList } = data
      return tableQueryOrderAddDTOList || []
    },
    setTableRulesData (data) {
      const { infoCheckAddDTOList, infoCheckQueryDTOList } = data
      const DTOList = infoCheckQueryDTOList || infoCheckAddDTOList
      return DTOList?.filter(item => item.changeRule !== 'notNull').map(item => {
        return {
          ...item,
          fields: item.columnKey.split(','),
          cid: nanoid(10),
          ruleInfo: item.ruleInfo,
          min: item.ruleInfo.indexOf('~') > -1 ? item.ruleInfo.split('~')[0] : '',
          max: item.ruleInfo.indexOf('~') > -1 ? item.ruleInfo.split('~')[1] : ''
        }
      }) || []
    },
    // 处理tableExConfig的数据
    filterTableExConfig (data) {
      const { tableForeignAddRepDTOList } = data
      this.tableExConfig.forEach((item, index) => {
        if (tableForeignAddRepDTOList && tableForeignAddRepDTOList[index]) {
          const { foreignId, foreignTableName, formId, formName } = tableForeignAddRepDTOList[index]
          item.subMeterId = foreignId || item.subMeterId
          item.subMeterName = foreignTableName || item.subMeterName
          item.meterId = formId || item.meterId
          item.meterName = formName || item.meterName
        }
      })
    },
    // // 函数，过滤并返回事件类型的中文含义数组
    // filterEventTypeChinese (eventTypeArr, eventTypeToChineseMap) {
    //   return eventTypeArr.map(eventType => eventTypeToChineseMap[eventType])
    // },
    // 重新设置路由
    // reRouter () {
    //   this.$router.matcher = new Router({
    //     mode: 'history',
    //     routes: constantRouterMap
    //   }).matcher
    //   this.$store
    //     .dispatch('GetInfo')
    //     .then(res => {
    //       this.$store.dispatch('GenerateRoutes', { data: res.data }).then(() => {
    //         // 动态添加可访问路由表
    //         this.$router.addRoutes(this.$store.getters.addRouters)
    //       })
    //     }).catch(() => {
    //     store.dispatch('GenerateRoutes', {}).then(() => {
    //       this.$router.addRoutes(store.getters.addRouters)
    //     })
    //   })
    // },
    handleCancel () {
      this.$emit('close')
      this.visible = false
    },
    handleConfirmCancel () {
      this.setFocusToFirstFocusableElement()
      this.$confirm({
        title: '提示',
        content: '确定取消吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.$emit('close')
          this.visible = false
        },
        onCancel: () => {}
      })
    },
    // 数据发送前预处理
    dataProcessing () {
      console.count('次数')
      // 处理外键关联，主表字段重新填充名字和字段key
      this.tableExConfig.forEach(item => {
        if (!item.masterMeterId) {
          item.data.forEach(e => {
            const data = this.pageData.find(sItem => sItem.cid === e.cid)
            e.masterMeter.dataIndex = data.formData.dataIndex
            e.masterMeter.name = data.formData.name
          })
        }
      })
      // 处理buttonData
      this.pageData.concat(this.defaultKeys).forEach(item => {
        const queryInfo = this.buttonData.find(buttonItem => buttonItem.buttonEventAddDTO.eventType === 'query')
        const addInfo = this.buttonData.find(buttonItem => buttonItem.buttonEventAddDTO.eventType === 'add')
        const updateInfo = this.buttonData.find(buttonItem => buttonItem.buttonEventAddDTO.eventType === 'update')
        // 默认按钮，默认字段不展示，表单字段展示。自定义按钮，根据展示字段赋值
        if (queryInfo.checked) {
          item.formData.columnQuery = queryInfo?.tableButtonAddDTO.defaultFlag ? item.name !== 'defaultKey' : queryInfo?.displayFields.includes(item.formData.dataIndex) || false
        } else {
          item.formData.columnQuery = false
        }
        if (addInfo.checked) {
          item.formData.columnAdd = addInfo?.tableButtonAddDTO.defaultFlag ? item.name !== 'defaultKey' : addInfo?.displayFields.includes(item.formData.dataIndex) || false
        } else {
          item.formData.columnAdd = false
        }
        if (updateInfo.checked) {
          item.formData.columnEdit = updateInfo?.tableButtonAddDTO.defaultFlag ? item.name !== 'defaultKey' : updateInfo?.displayFields.includes(item.formData.dataIndex) || false
        } else {
          item.formData.columnEdit = false
        }
      })
    },
    // 数据发送给后台前的处理
    dataAfterProcessing () {
      const pageData = this.pageData.filter(item => !item.hasOwnProperty('isSendData') || item.isSendData)
      return { pageData }
    },
    // 校验整个表单并返回错误信息
    async validateForm () {
      try {
        if (['add', 'edit'].includes(this.mode)) {
          this.basicActiveKey = '基本配置'
          // eslint-disable-next-line no-unused-expressions
          this.$refs.basicConfig?.setExKeyData() // 获取exKeysData数据，保证exKeysData存在
          await this.$refs.basicConfig.$refs.basicForm.validate() // 校验基础配置
          this.basicSubActiveKey = '数据库属性'
          await this.$refs.basicConfig.$refs.basicTableFrom.validate()
          this.basicSubActiveKey = '字段校验'
          await this.$nextTick(() => {})
          await this.$refs.basicConfig.$refs.tableRulesForm.validate() // 字段校验表单验证
        }

        // this.basicActiveKey = '表单设计'
        // await this.$refs.formRight.$refs.infoViews.$refs.form.validate() // 表单验证
      } catch (e) {
        console.error('错误信息', e)
        throw new Error('校验失败')
      }
    },
    // 保存表单
    async handleSave () {
      // 做校验
      // try {
        // await this.$refs.basicConfig.$refs.basicForm.validate() // 校验基础配置
        // await this.$refs.basicConfig.$refs.basicTableFrom.validate()
      // } catch (e) {
      //   console.error('校验失败', e)
      // }
      this.dataProcessing()// 发送前预处理数据
      // let groupIndex = 1
      const {
        basicData,
        pageData: _pageData,
        buttonData,
        allFormConfig,
        defaultKeys,
        tableExConfig,
        exKeysData,
        sortData,
        rulesData,
        tableDesc: {
          formId,
          tableButtonReqDTOList,
          tableQueryGroupReqDTOList,
          // checkGroupSimpleDTOList,
          checkGroupSimpleDTOList,
          checkGroupLinkageDTOList,
          tableQueryOrderAddDTOList,
          appId,
          appVersion,
          tableInfoAddDTO
        }
      } = this
      let tableQueryGroupAddDTOListGroupIndex = 0
      // eslint-disable-next-line no-unused-expressions
      tableQueryGroupReqDTOList?.map((item, index) => {
        item.tableQueryMappingAddDTO.groupIndex = index
        item.tableQueryGroupAddDTOList.map((item2) => {
          item2.groupIndex = tableQueryGroupAddDTOListGroupIndex
          if (item2.between && Object.keys(item2.between).length > 0) {
            item2.between[0].groupIndex = tableQueryGroupAddDTOListGroupIndex
            item2.between[1].groupIndex = tableQueryGroupAddDTOListGroupIndex
          }
          tableQueryGroupAddDTOListGroupIndex += 1
        })
      })
      if (_.isEmpty(_pageData) || _pageData.length === 0) {
        this.$message.warning('请先添加字段组件')
        return
      }
      if (_pageData.filter(item => item.isSendData).some(item => !item.formData.dataIndex)) {
        this.$message.warning('请填写所有的组件的数据绑定key')
        return
      }
       // 判断重名
      const fameButtonName = buttonData.filter((item, index) => index > _.cloneDeep(buttonGroup).length).some(item => _.cloneDeep(buttonGroup).map(e => e.tableButtonAddDTO.buttonName).includes(item.tableButtonAddDTO.buttonName))
      if (fameButtonName) {
        this.$message.warning('自定义按钮名称不能与系统默认按钮重名')
        return
      }
      await this.validateForm()

      const formUi = JSON.stringify({
        basicData,
        pageData: _pageData,
        exKeysData,
        defaultKeys,
        buttonData: _.map(buttonData, (item) => _.omit(item, ['eventColumnMappingAddDTOList', 'chartConfig'])),
        allFormConfig,
        // eslint-disable-next-line no-undef
        tableQueryGroupReqDTOList: tableQueryGroupReqDTOList,
        checkGroupSimpleDTOList: checkGroupSimpleDTOList,
        checkGroupLinkageDTOList: checkGroupLinkageDTOList,
        tableExConfig: tableExConfig.map(item => {
          return {
            ...item,
            keyOptions: [],
            columns: [],
            selectFields: {}
          }
        })
      })
      const { pageData } = this.dataAfterProcessing() // UI确定后发送到后台数据的处理
      const {
        formDescribe,
        formName,
        upFuncId,
        sort,
        dbRoleType,
        userGroupIds,
        primaryPrefix,
        prefixWay,
        appType,
        showType,
        upColumn,
        cardShowField,
        tenant,
        pseudoFlag,
        delFlag,
        columnList
      } = basicData
      let sendData
      // 数据源ID传给后台导入表单功能的时候要用
      const dataSourceUiMapDTOList = _pageData.filter(item => item.formData.dataSourceId).map(item => { // 数据源部分
        return { // 查询数据源
          dataColumnKey: item.formData.dataIndex,
          dataId: item.formData.dataSourceId,
          type: 'query',
          ruleId: item.cid,
          readUnlimited: item.formData.readUnlimited
        }
      }).concat(_pageData.filter(item => item.formData?.linkageConfig?.dataConfig?.length).map(item => { // 数据联动部分
        if (_.isArray(item.formData.linkageConfig.dataConfig)) { // 字段联动数据源
          return item.formData.linkageConfig.dataConfig.map(config => {
            if (config.plugInfo.componentType === 'dataSource') {
              return {
                dataColumnKey: item.formData.dataIndex,
                dataId: config.plugInfo.dataId,
                type: 'change',
                ruleId: config.cid,
                readUnlimited: item.formData.readUnlimited
              }
            }
          }).filter(Boolean)
        }
      }).flat(1)).concat(_pageData.filter(item => item.formData?.validateCondition?.dataSourceId).map(item => {
        return { // 校验数据源
          dataColumnKey: item.formData.dataIndex,
          dataId: item.formData?.validateCondition?.dataSourceId,
          type: 'check',
          ruleId: item.cid,
          readUnlimited: item.formData.readUnlimited
        }
      })).concat(_pageData.filter(item => item?.formData.type === 'table').flatMap(item => {
        // 表格列配置的数据源
        const { columns } = item.formData
        return columns.map(column => {
          const { controlType, cid, dataId } = column
          if (controlType === 'dataSource') {
            return {
              dataColumnKey: item.formData.dataIndex,
              dataId: dataId,
              type: 'tableColumn',
              ruleId: cid,
              readUnlimited: item.formData.readUnlimited
            }
          }
        }).filter(Boolean)
      }))
      console.log(dataSourceUiMapDTOList, 'dataSourceUiMapDTOList')
      // 子table的DTO
      const columnListInfoAddDTOList = _pageData.filter(item => item.formData.type === 'table' && item.formData.dataSource !== 'alone').map(item => {
        const { columns, dataIndex } = item.formData
        return _.unionBy(columns.filter(column => column.controlType !== 'total').map(column => {
          return {
            columnKey: dataIndex, // 控件key
            listName: column.title, // 列名
            listKey: column.dataIndex, // 数据库字段
            listType: column.dataType || '', // 数据类型
            typeFormat: column.typeFormat || '' // 数据格式
          }
        }).concat({
            columnKey: dataIndex, // 控件key
            listName: '_id', // 列名
            listKey: '_id', // 数据库字段
            listType: 'string' // 数据类型
        }), 'listKey')
      }).flat(1)
      if (['noCodeAdd', 'noCodeEdit'].includes(this.mode)) { // 无代码编辑或添加
        sendData = {
          formInfoAddDTO: {
            formId,
            formName: '',
            formUi
          },
          applicationInfoAddDTO: {
            appName: formName,
            oldAppName: this.oldAppName,
            appId: appId,
            appDesc: formDescribe,
            appVersion: '1.0.0',
            appType: appType,
            execType: appType
          },
          formInfoReqDTO: {
            columnInfoAddDTOList: pageData.map(item => {
              const { formData: { dataIndex: columnId, name: columnName } } = item
              return {
                columnId,
                columnName
              }
            }),
            columnOutputAddDTOList: buttonData.filter(e => e.columnOutputAddDTOList)?.[0]?.columnOutputAddDTOList || [],
            columnPlugAddDTOList: appType !== 'task' ? buttonData.filter(e => Array.isArray(e.columnPlugAddDTOList))[0].columnPlugAddDTOList : [],
            columnRelationAddDTOList: [],
            plugQueryAddDTOList: [],
            formExecOpLoadFileDTO: buttonData.filter(e => e.formExecOpLoadFileDTO).map(item => item.formExecOpLoadFileDTO)[0]
          },
          dataSourceUiMapDTOList: dataSourceUiMapDTOList,
          columnListInfoAddDTOList: columnListInfoAddDTOList
        }
      } else {
        // 处理规则数据，根据 rulesData 和 formData.required 创建对象列表
        const infoCheck = rulesData.map(item => {
          const { changeRule, fields, min, max, ruleInfo } = item
          return {
            changeRule: changeRule,
            columnKey: fields.join(','),
            // columnName,
            ruleInfo: ['numRange', 'length', 'size'].includes(changeRule) ? `${min || 0}~${max || ''}` : ruleInfo
          }
        }) || []
        // 检查是否存在至少一个必填项
        if (pageData.some(item => item.formData.required)) {
          // 补充必填校验规则给后台
          infoCheck.push({
            changeRule: 'notNull',
            columnKey: pageData.filter(item => item.formData.dataIndex && item.formData.required).map(item => item.formData.dataIndex).join(','),
            ruleInfo: ''
          })
        }
        // 处理表单控件信息
        sendData = {
          tableUiAddDTO: {
            formId,
            formUi
          },
          tableInfoAddDTO: {
            ...tableInfoAddDTO,
            formId,
            dbRoleType,
            groupList: dbRoleType === 'dataGroup' ? userGroupIds.length ? JSON.stringify(userGroupIds) : '' : '',
            columnList: ['dataColumn', 'upGroupColumn'].includes(dbRoleType) ? JSON.stringify(columnList) : '',
            dbType: 'monogo',
            formDescribe,
            formName,
            primaryPrefix: prefixWay === '1' ? primaryPrefix : '',
            showType,
            upColumn,
            cardShowField,
            tenant,
            pseudoFlag,
            delFlag
          },
          tableColumnInfoAddDTOList: pageData.concat(defaultKeys).map(item => {
            const {
              variable,
              formData: {
                columnAdd,
                columnEdit,
                columnQuery,
                typeFormat,
                dataIndex: columnKey,
                name: columnName,
                dataSource,
                dataType
              }
            } = item
            return {
              columnAdd,
              columnEdit,
              columnQuery,
              columnKey,
              columnName,
              columnType: variable === 'number' ? 'int' : variable || dataType, // 以前使用过number类型，已改为int，得兼容处理,只有默认字段使用variable，先都改用dataType
              typeFormat,
              dataSource
              // showColumn: dataSource === 'dataSource' ? dataOptionField.join(',').split('.')[1] : ''
            }
          }),
          tableButtonReqDTOList: formId ? buttonData.filter(item => item.checked).map((item, index) => {
            const tableButton = tableButtonReqDTOList?.find(c => c.tableButtonAddDTO.buttonName === item.tableButtonAddDTO.buttonName) || {}
            if (!_.isEmpty(tableButton)) {
              // 赋值不会影响buttonData
              // 切换自定义或原按钮，于新增时不一致则，eventId不赋值,defaultFlag注意数据类型后台返的是字符串
              if (String(tableButton.tableButtonAddDTO?.defaultFlag) === String(item.tableButtonAddDTO.defaultFlag)) {
                item.buttonEventAddDTO.eventId = tableButton.buttonEventAddDTO?.eventId || null
                item.tableButtonAddDTO.eventId = tableButton.tableButtonAddDTO?.eventId || null
              } else { // 当buttonData里有eventId
                delete item.buttonEventAddDTO.eventId
                delete item.tableButtonAddDTO.eventId
                item.buttonEventAddDTO.foreignId = undefined
              }
              tableButton.tableButtonAddDTO && Object.keys(tableButton.tableButtonAddDTO).forEach(key => { // 过滤字段
                if (!['buttonName', 'defaultFlag', 'eventId', 'menuFlag', 'buttonIcon', 'buttonType', 'buttonStyle'].includes(key)) {
                  item.tableButtonAddDTO[key] = tableButton.tableButtonAddDTO[key]
                }
              })
            }
            // 第一个查询增加增加菜单标识
            if (item.buttonEventAddDTO.eventType === 'query' && index === 0) {
              item.tableButtonAddDTO.menuFlag = '1'
            }
            // 自定义新增按钮，则要对应关系
            if (['add', 'del', 'update', 'query'].includes(item.buttonEventAddDTO.eventType) && item.tableButtonAddDTO.defaultFlag === false) {
              item.eventColumnMappingAddDTOList = item.displayFields.filter(key => {
                const item = this.pageData.find(e => e.formData.dataIndex === key)
                return item ? item.isSendData : true
              }).map(key => ({
                columnKey: key,
                foreignKey: key,
                handFilled: false
              }))
            // } else if (['add', 'del', 'update'].includes(item.buttonEventAddDTO.eventType) && item.hasOwnProperty('eventColumnMappingAddDTOList')) {
            } else if (['add', 'del', 'update', 'query'].includes(item.buttonEventAddDTO.eventType) && item.hasOwnProperty('eventColumnMappingAddDTOList')) {
              delete item.eventColumnMappingAddDTOList
            }
            return item
          }) : buttonData.filter(item => item.checked).map(item => {
            // 自定义新增按钮，则要对应关系
            if (['add', 'del', 'update', 'query'].includes(item.buttonEventAddDTO.eventType) && item.tableButtonAddDTO.defaultFlag === false) {
              item.eventColumnMappingAddDTOList = item.displayFields.filter(key => {
                const item = this.pageData.find(e => e.formData.dataIndex === key)
                return item ? item.isSendData : true
              }).map(key => ({
                columnKey: key,
                foreignKey: key,
                handFilled: false
              }))
            }
            return item
          }),
          infoCheckAddDTOList: infoCheck,
          // tableQueryGroupReqDTOList: pageData.concat(exKeysData).filter(item => item.formData.isSearch).map((item, index) => {
          //   const {
          //     formData: {
          //       searchDataKey,
          //       dataIndex: columnKey,
          //       nextRelation,
          //       condition,
          //       queryType,
          //       controlType,
          //       dataType
          //     }
          //   } = item

          //   const groupId = formUi ? tableQueryGroupReqDTOList?.find(item => item.tableQueryMappingAddDTO.queryKey === columnKey)?.tableQueryMappingAddDTO.groupId : ''
          //   const queryList = condition.map(e => {
          //     return {
          //       groupId,
          //       nextRelation,
          //       queryKey: ['1', '3'].includes(controlType) ? (searchDataKey || columnKey) : e.queryKey,
          //       // queryName: e.queryName,
          //       type: ['1', '3'].includes(controlType) ? queryType : e.queryType,
          //       groupIndex: groupIndex++,
          //       columnType: dataType
          //     }
          //   })
          //   return {
          //     tableQueryGroupAddDTOList: controlType === '2' ? queryList : [queryList[0]],
          //     tableQueryMappingAddDTO: {
          //       groupId,
          //       columnKey: searchDataKey || columnKey,
          //       groupIndex: index + 1,
          //       nextRelation
          //     }
          //   }
          // }),
          tableQueryGroupReqDTOList: tableQueryGroupReqDTOList,
          tableQueryOrderAddDTOList: sortData.filter(item => item.orderKey).map((item, orderIndex) => {
            const { orderKey, orderSort } = item
            return {
              orderId: formId ? tableQueryOrderAddDTOList?.find(item => item.orderKey === orderKey)?.orderId : '',
              orderKey,
              orderIndex,
              orderSort
            }
          }),
          funcInfoAddDTO: {
            upFuncId,
            sort
          },
          tableForeignAddRepDTOList: this.tableExConfig.map((item, index) => {
            const sItem = item.data[0]
            return {
              formId,
              index,
              foreignId: item.subMeterId,
              foreignShowColumn: item.displayFields.map(item => item.dataIndex).join(','),
              formTableName: item.masterMeterName,
              foreignTableName: item.subMeterName,
              showColumnAs: item.displayFields.map(item => item.anotherName).join(','),
              foreignRelationColumn: sItem.subMeter.dataIndex,
              mainColumn: sItem.masterMeter.dataIndex,
              showType: item.displayWay
            }
          }),
          dataSourceUiMapDTOList: dataSourceUiMapDTOList,
          columnListInfoAddDTOList: columnListInfoAddDTOList,
          checkGroupSimpleDTOList: checkGroupSimpleDTOList,
          checkGroupLinkageDTOList: checkGroupLinkageDTOList,
          sensitiveColumn: pageData.map(item => {
            if (item.formData.desensitization && item.formData.dataIndex) { return item.formData.dataIndex }
          }).filter(Boolean)
        }
      }
      console.log(sendData, '请求参数')
      console.log(formUi)
      try {
        if (['add', 'edit'].includes(this.mode)) { // 标准表单的添加和编辑请求
          this.confirmLoading = true
          const result = await this.$http.post(`/tableInfo/${formId ? 'tableEditSave' : 'saveTable'}`, sendData)
          console.log(result)
          if (result.data && result.data.length > 0) {
            this.$message.error(result.data)
            this.confirmLoading = false
          } else {
            this.visible = false
            this.reRouter() // 重新请求设置路由
            this.$message.success('提交成功')
          }
        } else if (['noCodeAdd', 'noCodeEdit'].includes(this.mode)) {
          this.confirmLoading = true
          const result = await this.$http.post(`/info/${formId ? 'saveMyApp' : 'saveMyApp'}`, sendData)
          // const result = await this.$http.post(this.mode === 'noCodeEdit' ? 'appEdit/saveNewVersion' : `/info/${formId ? 'saveMyApp' : 'saveMyApp'}`, sendData)
          console.log(result)
          const sendObj = { appName: formName, appVersion: appVersion }
          if (this.mode === 'noCodeEdit') sendObj.appId = appId
          await this.$http.post(`/info/saveLocalApp`, sendObj)
          this.visible = false
          this.reRouter() // 重新请求设置路由
          this.$message.success('提交成功')
        }
        console.log('输出内容', this.modeInfo, sendData)
        this.$emit('ok', this.modeInfo, sendData)
      } catch (e) {
        console.error('e', e)
        this.confirmLoading = false
      }
    },
    // 获取默认键名
    async queryDefaultKey () {
      try {
        const result = await this.$http.get('/tableInfo/queryDefaultKey')
        this.defaultKeys = result.data.map(item => {
          const { code: dataIndex, name, operate, variable, query } = item
          return ({
            cid: nanoid(),
            icon: 'edit',
            type: 'input',
            name: 'defaultKey',
            isSendData: true,
            operate,
            query,
            formData: {
              ...basicDefaultData(),
              dataType: variable,
              type: 'input',
              name,
              dataIndex,
              wrapperCol: 24,
              columnAdd: false,
              columnEdit: false,
              columnQuery: false
            }
          })
        })
      } catch (e) {
        console.error('请求错误', e)
        this.$message.error('请求默认字段接口报错，请联系管理员修复后，再进行操作')
        this.handleCancel()
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .arco-modal {
  width: 100vw !important;
  max-width: 100vw !important;
  top: 0;
  padding-bottom: 0;
}

/deep/ .arco-modal-body {
  height: calc(100vh - 60px);
  overflow-y: auto;
}

/deep/ .arco-tabs-nav-scroll {
  text-align: center;
}
</style>
